package org.sjtc.server;

import cn.hutool.core.util.StrUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.Arrays;
import java.util.List;

public class ServerReceiveHandler extends SimpleChannelInboundHandler<String> {
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, String msg) {
        String trim = msg.trim();
        String strip = StrUtil.strip(trim, "[", "]");
        // 添加下面4个handler
        // 添加中括号验证数据是否完整
        List<String> split = StrUtil.split(strip, "*");
        System.out.println("split list:"+split);
        String brand = split.get(0);
        String deviceId = split.get(1);
        String content = split.get(3);
        List<String> contentList = StrUtil.split(content, ",");
        System.out.println(contentList);
        String interfaceType = contentList.get(0);
        // 添加验证interfaceType是否存在
        // 添加按照interfaceType分别处理业务逻辑(调用不同的服务)
        System.out.println("interfaceType:"+contentList.get(0));
        System.out.println("brand:"+ brand);
        System.out.println("deviceId:"+ deviceId);
        System.out.println("content:"+ content);

        System.out.println("server receives message: " + msg.trim());
        // 添加返回数据的封装
        int length = interfaceType.length();
        String hexString = Integer.toHexString(length);
        String fourBitHexStr = StrUtil.padPre(hexString, 4, "0");
        String[] returnMsg = {brand, deviceId, fourBitHexStr, interfaceType};
        List<String> list = Arrays.asList(brand, deviceId, fourBitHexStr, interfaceType);
        String returnMsgStr = StrUtil.join("*", list);

        channelHandlerContext.writeAndFlush("["+returnMsgStr+"]");
    }
}
